#!/usr/bin/python3
import os, gc, shutil
from .Base_Plugin import Base_Plugin


class Server_Code_Async(Base_Plugin):
    """代码同步插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context

    def copy_and_replace(self, src, dst):
        if os.path.exists(dst):
            shutil.rmtree(dst)
        shutil.copytree(src, dst, dirs_exist_ok=True)

    def process(self, src, dst):
        for r in os.listdir(src):
            self.copy_and_replace(os.path.join(src, r), os.path.join(dst, r))

    def run(self, workspace, source):
        _code_storage = self.context["code_storage"]
        _root = _code_storage["root"]
        _target = _code_storage["target"]
        _source = f"""{self.context["workspace"]}\\{self.context["target"]}\\{self.context["code_target"]}"""
        _source_dir = os.path.join(_source, _root)
        _target_dir = os.path.join(_target, _root)
        self.process(_source_dir, _target_dir)
        self.processed += 1

        gc.collect()
        return source
